<template>
  <div>
    <div class="list-area">
      <div class="setting-area glo-content-area">
        <!-- <div class="title">陌生人访问开门报警记录</div> -->
        <div class="title">{{ $t("navigationLeft.accessRecord") }}</div>
      </div>

      <div class="glo-search-area">
        <div class="widget-item">
          <div class="widget-label">{{ $t("AccessIndex.AccessOpenDoorType") }}</div>
          <Select
            v-model="personType"
          >
            <Option
              v-for="(item, idx) in personTypes" :key="idx"
              :value="item.value"
              :label="item.name"
            ></Option>
          </Select>
        </div>
        <div class="widget-item glo-clear-after">
          <div class="widget-label">{{ $t("staffIndex.staffDepartCrewName") }}</div>
          <Input
            v-model="personName"
            :placeholder="$t('staffIndex.staffDepartCrewSearch')"
            search
            :enter-button="$t('devicesIndex.devNumberBtn')"
            @on-search="$_page_update"
          />
        </div>

        <div class="widget-item glo-clear-after">
          <div class="widget-label">{{ $t("devicesIndex.devNumberName") }}：</div>
          <Input
            v-model="sn"
            :placeholder="$t('devicesIndex.devNumberHint')"
            search
            :enter-button="$t('devicesIndex.devNumberBtn')"
            @on-search="$_page_update"
          />
        </div>

        <div class="widget-item glo-clear-after">
          <div class="widget-label">{{ $t("newDevices.siteName") }}：</div>
          <Input
            v-model="areaName"
            :placeholder="$t('companyManagement.pleaseEnter')+$t('newDevices.siteName')"
            search
            :enter-button="$t('devicesIndex.devNumberBtn')"
            @on-search="$_page_update"
          />
        </div>
        <div class="widget-item glo-clear-after">
          <div class="widget-label">{{ $t("BodyTemperatureIndex.BodyTemAnimalTimeS") }}</div>
          <DatePicker
            class="date-widget"
            v-model="selectDate"
            type="daterange"
            :editable='false'
            :clearable="false"
            :placeholder="$t('BodyTemperatureIndex.BodyTemAnimalTimeScope')"
          />
        </div>
        <div class="widget-item glo-clear-after" v-if="allPermissions.staffFailureLog1">
          <i-button style="margin-top: 36px;"  type="primary" @click="downloadClick" >{{$t('BodyTemperatureIndex.BodyTemAnimalRecord')}}</i-button>
        </div>
        

        <!-- <div class="date-filter widget-item">
          <div class="widget-label">日期筛选：</div>
          <DatePicker
            class="date-widget"
            v-model="selectDate"
            type="daterange"
            placeholder="记录的时间范围"
          />
        </div> -->
      </div>

      <!-- <div class="glo-selection">
        <Alert show-icon>
          已选择 {{ selection.length }} 项
          <a class="glo-selection-clean" @click="handleSelectionAllStatus(false)">清空</a>
        </Alert>
      </div> -->
      <Table
        ref="table"
        class="list"
        :data="list"
        :columns="columns"
        @on-selection-change="handleSelection"
      />
      <Page
        class="glo-content-area glo-pagenation"
        :total="total"
        :pageSize="pageSize"
        show-sizer
        :current="page"
        show-total
        @on-change="$_page_pageChange"
        @on-page-size-change="$_page_pageSizeChange"
      />
    </div>
  </div>
</template>

<script>
import {
  mapState,
} from 'vuex'
import moment from 'moment'
import {
  getAccess,
  exportVisitorList
} from '@/api/record.js'
import {
  getPhoto,
  getExcel
} from '@/api/public.js'

import pageMixin from '@/utils/mixins/pageMixin.js'

// import ListSettings from './ListSettings'

export default {
  mixins: [
    pageMixin,
  ],

  data () {
    return {
      personName: '',
      sn: '',
      areaName: '',
      // selectDate: [],
      personType: '',
      personTypes: [
        { name: this.$t('AccessIndex.AccessOpenDoorFace'), value: '1' },
        { name: this.$t('AccessIndex.AccessOpenDoorPass'), value: '2' },
        { name: this.$t('AccessIndex.AccessOpenDoorApp'), value: '3' },
        { name: this.$t('AccessIndex.AccessOpenDoorID'), value: '4' },
        { name: this.$t('AccessIndex.AccessOpenDoorID5'), value: '5' },
        { name: this.$t('AccessIndex.AccessOpenDoorID6'), value: '6' },
        { name: this.$t('AccessIndex.AccessOpenDoorID7'), value: '7' },
        { name: this.$t('AccessIndex.AccessOpenDoorID8'), value: '8' },
      ],
      selection: [],
      list: [],
      page:1,
      columns: [
        { type: 'selection', width: 70 },
        {
          type: 'index',
          width: 60,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('devicesIndex.devTableserial'),
          key: 'sn',
        },
        {
          title: this.$t('devicesIndex.devTableName'),
          key: 'deviceName',
        },
        {
          title: this.$t('AccessIndex.AccessPersonName'),
          key: 'username',
          render: (h, { row }) => {
            let label = '-'
            if (row.username) {
              label = row.username
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('AccessIndex.AccessJobNum'),
          key: 'worknum',
          render: (h, { row }) => {
            let label = '-'
            if (row.worknum) {
              label = row.worknum
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('newDevices.siteName'),
          key: 'areaName',
          render: (h, { row }) => {
            let label = row.areaName
            if (row.areaName=='新场所') {
              label = this.$t('title.newSite')
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('AccessIndex.AccessOpenDoorType'),
          key: 'unlockType ',
          render: (h, { row }) => {
            let label = '-'
            let labelID = ''
            if (row.unlockType == '1') {
              label = this.$t('AccessIndex.AccessOpenDoorFace')
            } else if (row.unlockType == '2') {
              label = this.$t('AccessIndex.AccessOpenDoorPass')
            } 
            else if (row.unlockType == '3') {
              label = this.$t('AccessIndex.AccessOpenDoorApp')
            } 
            else if (row.unlockType == '4') {
              label = this.$t('AccessIndex.AccessOpenDoorID')
              let sexIs = this.$t('staffIndex.staffDepartMan')
              if (row.sex == 1) {
                sexIs = this.$t('staffIndex.staffDepartMan')
              } else {
                sexIs = this.$t('staffIndex.staffDepartWoman')
              }
              labelID = `${row.realName}-${sexIs}-${row.birthday}`
            }
            else if (row.unlockType == '5') {
              label = this.$t('AccessIndex.AccessOpenDoorID5')
            } 
            else if (row.unlockType == '6') {
              label = this.$t('AccessIndex.AccessOpenDoorID6')
            } 
            else if (row.unlockType == '7') {
              label = this.$t('AccessIndex.AccessOpenDoorID7')
            } 
            else if (row.unlockType == '8') {
              label = this.$t('AccessIndex.AccessOpenDoorID8')
            } 
            
            return h('div', [h('span', {
              domProps: {
                title: labelID,
              }
            }, label)

            ])
          },
        },
        {
          title: this.$t('AccessIndex.AccessrealName'),
          key: 'realName',
        },
        {
          title: this.$t('AccessIndex.AccessTransittTime'),
          key: 'unlockTime',
        },
        {
          title: this.$t('AccessIndex.AccessSitePhotos'),
          key: 'photo',
          render: (h, { row }) => {
            if (!row.photo || row.photo === '') {
              return h('div', '-')
            }
            return h('div', {
              class: 'img-area',
            }, [

              h('Tooltip', {
                props: {
                  placement: 'top-start',
                  transfer: true,
                }
              }, [
                h('viewer', [
                  h('img', {
                    style: {
                      cursor: 'pointer',
                    },
                    attrs: {
                      src: getPhoto(row.photo),
                    },
                  }),
                ]), h('span', {
                  slot: 'content',
                  style: {
                    whiteSpace: 'normal',
                  }
                }, this.$t('title.clickBig')),

              ])
            ])
          },
        },
      ],

      ifCreate: false,
      ifUpdate: false,
      editItem: null,
      ifSelectArea: false,
      areaSelectCallback: null,
      allPermissions:{
        staffFailureLog1:false,
      },
      selectDate: [],
      beginTime:'',
      endTime:'',
    }
  },
  computed: {
    ...mapState([
      'departId',
    ]),
    btnShow () {
      return this.$store.state.btnShow
    },
  },
  watch: {
    // personType: 'update',
    personType: '$_page_update',
    selectDate: '$_page_update',
    btnShow () {
      
      this.personTypes = [
        { name: this.$t('AccessIndex.AccessOpenDoorFace'), value: '1' },
        { name: this.$t('AccessIndex.AccessOpenDoorPass'), value: '2' },
        { name: this.$t('AccessIndex.AccessOpenDoorApp'), value: '3' },
        { name: this.$t('AccessIndex.AccessOpenDoorID'), value: '4' },
        { name: this.$t('AccessIndex.AccessOpenDoorID5'), value: '5' },
        { name: this.$t('AccessIndex.AccessOpenDoorID6'), value: '6' },
        { name: this.$t('AccessIndex.AccessOpenDoorID7'), value: '7' },
        { name: this.$t('AccessIndex.AccessOpenDoorID8'), value: '8' },
      ]

      this.columns = [
        { type: 'selection', width: 70 },
        {
          type: 'index',
          width: 60,
          indexMethod: this.$_index_method,
        },
        {
          title: this.$t('devicesIndex.devTableserial'),
          key: 'sn',
        },
        {
          title: this.$t('devicesIndex.devTableName'),
          key: 'deviceName',
        },
        {
          title: this.$t('AccessIndex.AccessPersonName'),
          key: 'username',
          render: (h, { row }) => {
            let label = '-'
            if (row.username) {
              label = row.username
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('AccessIndex.AccessJobNum'),
          key: 'worknum',
          render: (h, { row }) => {
            let label = '-'
            if (row.worknum) {
              label = row.worknum
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('newDevices.siteName'),
          key: 'areaName',
          render: (h, { row }) => {
            let label = row.areaName
            if (row.areaName=='新场所') {
              label = this.$t('title.newSite')
            }
            return h('div', label)
          },
        },
        {
          title: this.$t('AccessIndex.AccessOpenDoorType'),
          key: 'unlockType ',
          render: (h, { row }) => {
            let label = '-'
            let labelID = ''
            if (row.unlockType == '1') {
              label = this.$t('AccessIndex.AccessOpenDoorFace')
            } else if (row.unlockType == '2') {
              label = this.$t('AccessIndex.AccessOpenDoorPass')
            } else if (row.unlockType == '3') {
              label = this.$t('AccessIndex.AccessOpenDoorApp')
            } else if (row.unlockType == '4') {
              label = this.$t('AccessIndex.AccessOpenDoorID')
              let sexIs = this.$t('staffIndex.staffDepartMan')
              if (row.sex == 1) {
                sexIs = this.$t('staffIndex.staffDepartMan')
              } else {
                sexIs = this.$t('staffIndex.staffDepartWoman')
              }
              labelID = `${row.realName}-${sexIs}-${row.birthday}`
            }
            else if (row.unlockType == '5') {
              label = this.$t('AccessIndex.AccessOpenDoorID5')
            } 
            else if (row.unlockType == '6') {
              label = this.$t('AccessIndex.AccessOpenDoorID6')
            } 
            else if (row.unlockType == '7') {
              label = this.$t('AccessIndex.AccessOpenDoorID7')
            } 
            else if (row.unlockType == '8') {
              label = this.$t('AccessIndex.AccessOpenDoorID8')
            } 
            
            return h('div', [h('span', {
              domProps: {
                title: labelID
              }
            } ,label)

            ])
          },
        },
        {
          title: this.$t('AccessIndex.AccessrealName'),
          key: 'realName',
        },
        {
          title: this.$t('AccessIndex.AccessTransittTime'),
          key: 'unlockTime',
        },
        {
          title: this.$t('AccessIndex.AccessSitePhotos'),
          key: 'photo',
          render: (h, { row }) => {
            if (!row.photo || row.photo === '') {
              return h('div', '-')
            }
            return h('div', {
              class: 'img-area',
            }, [

              h('Tooltip', {
                props: {
                  placement: 'top-start',
                  transfer: true,
                }
              }, [
                h('viewer', [
                  h('img', {
                    style: {
                      cursor: 'pointer',
                    },
                    attrs: {
                      src: getPhoto(row.photo),
                    },
                  }),
                ]), h('span', {
                  slot: 'content',
                  style: {
                    whiteSpace: 'normal',
                  }
                }, this.$t('title.clickBig')),

              ])
            ])
          },
        },
      ];

      return this.$store.state.btnShow
    }
  },
  created () {
    this.getWeekDate()
  },
  mounted () {
    this.$_page_update()
    this.getAllPermissions()
  },

  methods: {
    update(){
      this.page=1
      this.getData({
        page: this.page,
        pageSize: this.pageSize,
      })
      console.log('page',this.page)
    },
    getWeekDate(){
      var myDate = new Date(); 
      var befordata = myDate.getTime()-6*24*3600*1000
      function timestampToTime(timestamp) {
        var date = new Date(timestamp);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        var D = date.getDate()<10 ? '0'+date.getDate() : date.getDate();
        return Y+M+D;
      }
      this.beginTime=(timestampToTime(befordata));
      var year = myDate.getFullYear(); 
      var month = myDate.getMonth()+1;
      var day = myDate.getDate();//获取当前日（1-31） 
      if (month<10) { month = "0" + month; } 
      if (day >= 0 && day <= 9) {
        if (day == 1) {
        month = myDate.getMonth()
        if(month==0) {
        month=12; year=year-1; 
        }
        day = new Date(year, month, 0).getDate ();
        } else {
        day = day < 10 ? "0" + day : day 
        } 
      }
      var days = day-6;
      days = days<10 ? "0"+days:days;
      this.endTime = year+"-"+month + "-" + day;
      // console.log('xingqi',this.beginTime,this.endTime)
      this.selectDate=[this.beginTime,this.endTime]
    },
    getAllPermissions(){
      let da=JSON.parse(window.localStorage.getItem('logo'))||[]
      da.map(v => {
        if(v.permission=='#accessRecord'&&v.children){
          v.children.map(a=>{
            if(a.permission=='#staffFailureLog1'&&a.checked==='true'){
              this.allPermissions.staffFailureLog1=true
            }
          })
        }
      });
    },
    handleSelection (selection = []) {
      this.selection = selection
    },
    handleSelectionAllStatus (status) {
      this.$refs.table.selectAll(status)
    },

    handleSettingsClick (name, row) {
      switch (name) {
        case 'edit':
          this.showUpdate(row)
          break
      }
    },

    async getData (query) {
      var startTime='',endTime=''
      if (this.selectDate.length) {
        const [startDate, endDate] = this.selectDate
        if (moment.isDate(startDate)) {
          startTime = moment(startDate).format('YYYY-MM-DD')
        }
        if (moment.isDate(endDate)) {
          endTime = moment(endDate).format('YYYY-MM-DD')
        }
      }
      let areaName=''
      console.log('this.areaName',this.areaName,this.$t('title.newSite'))
      if(this.areaName==this.$t('title.newSite')){
        areaName="新场所"
      }else{
        areaName=this.areaName
      }
      const { success, data } = await getAccess({
        page: query.page,
        limit: query.pageSize,
        // departId: this.departId,
        username: this.personName,
        sn: this.sn,
        areaName,
        unlockType: this.personType,
        startTime,
        endTime,
      })
      let list = []
      let page = 1
      let total = 0
      if (success) {
        list = data.data
        page = data.pageNum || 1
        total = Number(data.count)
      }
      this.list = list
      this.page = page
      this.pageSize = query.pageSize
      this.total = total
      this.selection = []
    },
    async downloadClick () {
      this.getExportList()
    },
    async getExportList (query) {
      let language = localStorage.getItem('language') || 'zh'
      switch (language) {
        case 'zh':
          language = 1
          break
        case 'zf':
          language = 2
          break
        case 'en':
          language = 3
          break
        case 'ja':
          language = 4
          break
        case 'ko':
          language = 5
          break
      }
      var startTime='',endTime=''
      if (this.selectDate.length) {
        const [startDate, endDate] = this.selectDate
        if (moment.isDate(startDate)) {
          startTime = moment(startDate).format('YYYY-MM-DD')
        }
        if (moment.isDate(endDate)) {
          endTime = moment(endDate).format('YYYY-MM-DD')
        }
      }
      let areaName
      if(this.areaName==this.$t('title.newSite')){
        areaName='新场所'
      }else{
        areaName=this.areaName
      }
      const baseQuery = {
        username: this.personName,
        sn: this.sn,
        areaName: areaName,
        unlockType: this.personType,
        language: language,
        startTime,
        endTime,
      }
      const { success, data } = await exportVisitorList(baseQuery)
      if (success) {
        if (data.code == 0) {
          window.open(getExcel(data.msg))
        }else{
          this.$Message.error(this.$t('BodyTemperatureIndex.BodyTemAnimalRecordErr'))
        }
      }else{
        if(data=='免费版不支持导出'){
          this.$Message.error(this.$t('BodyTemperatureIndex.BodyTemAnimalRecordErr1'))
        }else if(data=='授权文件已损坏'){
          this.$Message.error(this.$t('BodyTemperatureIndex.BodyTemAnimalRecordErr2'))
        }else{
          this.$Message.error(this.$t('BodyTemperatureIndex.BodyTemAnimalRecordErr'))
        }
      }
    },
  },
}
</script>

<style lang="less" scoped>
.list-area {
  overflow: hidden;

  /deep/ .img-area {
    width: 100px;
    height: 100px;
    margin: 6px 0;
    box-sizing: content-box;
    overflow: hidden;
    img {
      width: 100%;
    }
  }
}
.setting-area {
  .clearfix();

  .btns {
    float: right;
  }
  .title {
    line-height: @lh-base;
    font-size: 18px;
    font-weight: bold;
  }
}
.glo-search-area {
  .date-filter {
    .date-widget {
      width: 210px;
    }
  }
}
</style>
